﻿using System;
using System.Web.Mvc;
using Kaiser.Infrastructure.Controllers;
using Kaiser.Modules.Hiner.Models.Product;
using Kaiser.Modules.Hiner.Services;
using Kaiser.Modules.Hiner.Models.Product.SearchModels;
using Kaiser.Models;
using Kaiser.Models.JsonModels;
using Kaiser.Extensions;
using System.Web.Script.Serialization;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Data;

namespace Kaiser.Modules.Hiner.Controllers
{
    public class ProductManageController : KaiserBaseController
    {
        #region 变量和属性
        private readonly IProductService _productService;

        public ProductManageController(IProductService productService)
        {
            this._productService = productService;
        }


        #endregion

        public ActionResult ProductList()
        {

            return View();
        }

        /// <summary>
        /// 产品列表
        /// </summary>
        /// <param name="search"></param>
        /// <param name="pageinfo"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ProductList(ProductSearch search, PagingInfo pageinfo, FormCollection form)
        {
            var result = _productService.SearchProduct(search, pageinfo);

            return Content(result.ToJsonString());
        }

        public ActionResult GetProductList(ProductSearch search, PagingInfo pageinfo)
        {
            DataTable dt = _productService.GetProductList(search, pageinfo);

            ViewBag.dt = dt;
            return View();
        }

        [HttpPost]
        public ActionResult AddProduct(ProductBase model)
        {
            var result = new JsonReturnMessages();

            try
            {

                model.CreateDateTime = DateTime.Now;
                model.CreateUserFullName = User.Identity.Name;
                model.CreateUserName = CurrentUser.Name;

                _productService.Insert(model);

                result.success = true;
                result.msg = "保存成功！";
            }
            catch (Exception ex)
            {
                result.success = false;
                result.msg = ex.Message;
            }
            return Json(result, "text/html");
        }


        public ActionResult AddProduct()
        {
            var model = new ProductBase();
            model.ProductId = Guid.NewGuid().GenerateGuid().ToString();
            return View("EditProduct", model);
            //return EditProduct("", model, form);
        }

        public ActionResult EditProduct(string id)
        {
            ProductBase model = _productService.Get(id);

            return View(model);
        }


        /// <summary>
        /// 编辑产品
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditProduct(string id, ProductBase model, FormCollection form)
        {
            var result = new JsonReturnMessages();

            try
            {

                if (id.IsNullOrWhiteSpace())
                {
                    model.ProductId = Guid.NewGuid().GenerateGuid().ToString();
                    model.CreateDateTime = DateTime.Now;
                    model.CreateUserFullName = User.Identity.Name;
                    model.CreateUserName = CurrentUser.Name;

                    _productService.Insert(model);
                }
                else
                {
                    ProductBase oldSort = _productService.Get(id);
                    model.CreateDateTime = oldSort.CreateDateTime;
                    model.CreateUserFullName = oldSort.CreateUserFullName;
                    model.CreateUserName = oldSort.CreateUserName;
                    model.LastModifyDateTime = DateTime.Now;
                    model.LastModifyUserFullName = User.Identity.Name;
                    model.LastModifyUserName = CurrentUser.Name;
                    _productService.Update(model);
                }
                result.success = true;
                result.msg = "保存成功！";
            }
            catch (Exception ex)
            {
                result.success = false;
                result.msg = ex.Message;
            }
            return Json(result, "text/html");
        }

        /// <summary>
        /// 批量删除产品
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelProduct(string ids)
        {
            var result = new JsonReturnMessages();
            if (!ids.IsNullOrWhiteSpace())
            {
                try
                {

                    _productService.Delete(ids);
                    result.success = true;
                    result.msg = "删除成功！";

                }
                catch (Exception ex)
                {
                    result.success = false;
                    result.msg = ex.Message;

                }
            }
            else
            {
                result.success = false;
                result.msg = "传值失败，请告诉开发者解决";
            }
            var json = new JavaScriptSerializer();
            return Content(json.Serialize(result), "text/html;charset=UTF-8");
        }

        public ActionResult ProductDetail(string id)
        {
            ProductBase oldSort = _productService.Get(id);
            return View(oldSort);
        }

        #region 上传


        /// <summary>
        /// 新增产品
        /// </summary>
        /// <param name="model"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadFilesList(AttachmentSearch model, PagingInfo pageinfo, FormCollection form)
        {
            var result = _productService.GetAttachmentList(model, pageinfo);
            return Content(result.ToJsonString());
        }
        public ActionResult UploadFilesList()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadFiles(FormCollection form)
        {
            JsonReturnMessages result = new JsonReturnMessages();
            //context.Response.ContentType = "text/html";

            var file = Request.Files[0];
            if (file.ContentLength == 0)
            {
                //文件大小大（以字节为单位）为0时，做一些操作
                return View();
            }
            else
            {

                //判断文件是否存在，不存在就创建
                string url = @"\UploadFile\" + DateTime.Now.Year.ToString() + @"\" + DateTime.Now.Month.ToString("d2") + @"\" + DateTime.Now.Day.ToString("d2");
                if (CheckDirectory(Server.MapPath(url)))
                {
                    string Saveurl = "";
                    try
                    {
                        string code = form["ObjectID"];
                        string strFullFileName = System.IO.Path.GetFileName(file.FileName);
                        string strFileName = strFullFileName.Substring(strFullFileName.LastIndexOf('\\') + 1);
                        //保存成自己的文件全路径,newfile就是你上传后保存的文件,
                        //服务器上的UpLoadFile文件夹必须有读写权限　
                        //System.IO.Path.()
                        var idx = strFileName.LastIndexOf('.');
                        string fileName = Guid.NewGuid().ToString() + strFileName.Substring(idx, strFileName.Length - idx);
                        Saveurl = url + "/" + fileName;
                        string fileNameurl = Server.MapPath(url + "\\") + fileName;
                        file.SaveAs(fileNameurl);
                        Attachment model = new Attachment();
                        model.Attach_ContentType = file.ContentType;
                        model.Attach_CreateTime = DateTime.Now;
                        model.Attach_FileName = strFileName;
                        model.Attach_ObjectID = form["ObjectID"];
                        model.Attach_ObjectModule = form["ObjectModule"];
                        model.Attach_Path = Saveurl;
                        model.Attach_Size = file.ContentLength;
                        int ID = 0;
                        if (_productService.GetAttachmentList(new AttachmentSearch() { Attach_ObjectID = code, Attach_ObjectModule = form["ObjectModule"] }, new PagingInfo() { Index = 0, Size = int.MaxValue }).rows.Count != 0 && "HinnerOrder".Equals(form["ObjectModule"]))
                        {
                            _productService.DeleteAttachment(_productService.GetAttachmentList(new AttachmentSearch() { Attach_ObjectID = code, Attach_ObjectModule = form["ObjectModule"] }, new PagingInfo() { Index = 0, Size = int.MaxValue }).rows[0].Attach_ID.ToString());
                        }
                        ID = _productService.InsertAttachment(model);
                        result.msg = "";
                        result.Data = new { FileName = strFullFileName, FilePath = Saveurl, Size = file.ContentLength, ID = ID };
                    }
                    catch
                    {
                        FileInfo info = new FileInfo(Server.MapPath(Saveurl));
                        if (info != null)
                        {
                            info.Delete();
                        }
                    }
                }
            }
            JavaScriptSerializer json = new JavaScriptSerializer();
            return Content(json.Serialize(result), "text/html;charset=UTF-8");
        }


        /// <summary>
        /// 检查目录是否存在，如果不存在，层层创建它
        /// </summary>
        /// <param name="strDir"></param>
        /// <returns></returns>
        public static bool CheckDirectory(string strDir)
        {
            bool bolRes = false;
            //检查路径是否存在，如果不存在，创建该路径
            if (Directory.Exists(strDir) == false)
            {
                try
                {
                    //创建路径
                    Directory.CreateDirectory(strDir);
                    bolRes = true;
                }
                catch (Exception ex)
                {
                    bolRes = false;
                }
            }
            else
            {
                bolRes = true;
            }
            return bolRes;
        }



        /// <summary>
        /// 批量删除产品
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelAttachment(string ids, FormCollection form)
        {
            var result = new JsonReturnMessages();
            if (!ids.IsNullOrWhiteSpace() || !form["ids"].IsNullOrWhiteSpace())
            {
                try
                {
                    List<FileInfo> list = new List<FileInfo>();
                    foreach (var item in ids.Trim(',').Split(','))
                    {
                        Attachment model = _productService.GetAttachment(item);
                        FileInfo info = new FileInfo(Server.MapPath(model.Attach_Path));
                        if (info != null)
                        {
                            info.Delete();
                        }
                    }
                    _productService.DeleteAttachment(ids);
                    result.msg = "删除成功";
                    result.success = true;
                }
                catch (Exception)
                {
                    result.msg = "删除失败";
                    result.success = false;
                }
            }
            else
            {
                result.msg = "传值失败，请告诉开发者解决";
            }
            if (!form["url"].IsNullOrWhiteSpace())
            {
                FileInfo info = new FileInfo(Server.MapPath(form["url"]));
                if (info != null)
                {
                    info.Delete();
                }
                result.msg = "删除成功";
                result.success = true;
            }
            else
            {
                result.msg = "传值失败，请告诉开发者解决";
                result.success = false;
            }
            var json = new JavaScriptSerializer();
            return Content(json.Serialize(result), "text/html;charset=UTF-8");
        }
        #endregion

        #region 下载
        public FileStreamResult ViewFile(string FileID)
        {
            Attachment model = new Attachment();
            model = _productService.GetAttachment(FileID);

            return File(new FileStream(AppDomain.CurrentDomain.BaseDirectory + model.Attach_Path, FileMode.Open), "text/plain", model.Attach_FileName);
        }
        #endregion

        public ActionResult ValidHDECode(string code, string id)
        {
            return Content(_productService.ValidHDECode(code, id).GetHashCode().ToString());

        }

        public ActionResult ValidHinerCode(string code, string id)
        {
            return Content(_productService.VaidHinerCode(code, id).GetHashCode().ToString());

        }

    }
}
